package com.csot.service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;

import org.springframework.beans.BeanUtils;

import com.csot.model.CoarseIp;
import com.csot.model.CoarseSegment;
import com.jfinal.plugin.activerecord.Db;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.thread.ThreadUtil;

public class IpCoarseSegmentDetail implements Runnable {

	static final ExecutorService coarseExecutorService = ThreadUtil.newSingleExecutor();

	@Override
	public void run() {
		// TODO Auto-generated method stub

		List<CoarseSegment> csList = getSlot();
		if (CollUtil.isEmpty(csList)) {
			return;
		}

		csList.forEach(f -> {
			coarseExecutorService.execute(() -> {
				Db.tx(() -> {
					List<CoarseIp> ciList = new ArrayList<>();
					for (long i = f.getIpStartI(); i <= f.getIpEndI(); i++) {
						CoarseIp ci = new CoarseIp();
						BeanUtils.copyProperties(f, ci, "id");
						ci.setIpAddressI(i);
						ci.setIpAddress(NetUtil.longToIpv4(i));
						ci.setIpSegmentId(f.getId());
						ciList.add(ci);
					}
					Db.batchSave(ciList, 99);
					return true;
				});
			});
		});

	}

	public List<CoarseSegment> getSlot() {
		// TODO Auto-generated method stub

		CoarseSegment dao = new CoarseSegment().dao();
		List<CoarseSegment> csList = dao
				.find("select * from t_coarse_segment t where id not IN (select ip_segment_id from t_coarse_ip)");
		return csList;

	}

}
